package org.mj.im.server.netty.ws;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.mj.im.server.netty.IMNettyServer;
import org.mj.im.server.netty.handler.IMChannelHandler;
import org.mj.im.server.netty.ws.codec.WebSocketMessageEncoder;
import org.mj.im.server.netty.ws.codec.WebsocketMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnProperty(prefix = "im.server.websocket",value = "enable",havingValue = "true",matchIfMissing = true)
public class WebsocketServer implements IMNettyServer {
    private final Logger logger = LoggerFactory.getLogger(WebsocketServer.class);
    private volatile boolean ready = false;

    @Value("${im.server.websocket.port}")
    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;


    @Override
    public boolean ready() {
        return ready;
    }



    @Override
    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                pipeline
                        .addLast(new IdleStateHandler(120,0,0, TimeUnit.SECONDS))
                        .addLast("http-codec",new HttpServerCodec())
                        .addLast("aggregator",new HttpObjectAggregator(65536))
                        .addLast("http-chunked",new ChunkedWriteHandler())
                        .addLast(new WebSocketServerProtocolHandler("/im"))
                        .addLast("encode",new WebSocketMessageEncoder())
                        .addLast("decode",new WebsocketMessageDecoder())
                        .addLast("handler",new IMChannelHandler());
            }
        }).option(ChannelOption.SO_BACKLOG,5)
                .childOption(ChannelOption.SO_KEEPALIVE,true);
        try{
            bootstrap.bind(port).sync().channel();
            this.ready = true;
            logger.info("IM server started on port {}", port);
        }catch (InterruptedException e){
            logger.error("IM server start error", e);
        }
    }

    @Override
    public void stop() {
        if (bossGroup != null && !bossGroup.isShutdown() && !bossGroup.isShuttingDown()) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null && !workerGroup.isShutdown() && !workerGroup.isShutdown()) {
            workerGroup.shutdownGracefully();
        }
        this.ready = false;
        logger.info("IM server stopped");
    }
}
